package com.easemob.helpdesk.activity.history;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.bean.User;
import com.easemob.helpdesk.bean.UserInfo;
import com.easemob.helpdesk.utils.CommonUtils;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.R;
//import com.easemob.helpdesk.activity.BaseActivity;
import com.easemob.helpdesk.activity.BaseActivityV2;
import com.easemob.helpdesk.adapter.HistoryListAdapter;
import com.easemob.helpdesk.widget.recyclerview.DividerLine;
//import com.hyphenate.kefusdk.bean.HistorySessionEntity;
//import com.hyphenate.kefusdk.entity.HDVisitorUser;
import com.hyphenate.kefusdk.entity.HistorySessionEntity;
import com.hyphenate.kefusdk.entity.user.HDVisitorUser;
import com.hyphenate.kefusdk.utils.HDLog;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;

//import okhttp3.OkHttpClient;

/**
 * Created by liyuzhao on 16/3/15.
 */
public class SearchHistorySessionActivity extends BaseActivityV2 {


    private static final String TAG = SearchHistorySessionActivity.class.getSimpleName();

    private EasyRecyclerView recyclerView;
    private ImageButton btnClear;
    private EditText query;
    private RelativeLayout rl_back;
    private ArrayList<HistorySessionEntity> mList = new ArrayList<>();
    private HistoryListAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_history_session);
        initView();
        ArrayList<HistorySessionEntity> list = getIntent().getParcelableArrayListExtra("list");
        if(list != null && list.size() > 0){
            for (int i=0; i < list.size(); i++){
                HistorySessionEntity entity = list.get(i);
                getUserInfo(entity);
                mList.add(entity);
            }
//            mList.addAll(list);
        }

        final LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        //设置分割线
        DividerLine dividerLine = new DividerLine(DividerLine.VERTICAL);
        dividerLine.setSize(1);
        dividerLine.setColor(0xFFDDDDDD);
        recyclerView.addItemDecoration(dividerLine);

        recyclerView.setAdapterWithProgress(mAdapter = new HistoryListAdapter(this));
        mAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int i) {
                HistorySessionEntity entty = mAdapter.getItem(i);
                String sServiceId = entty.serviceSessionId;
                HDVisitorUser toUser = entty.visitorUser;
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), HistoryChatActivity.class);
                intent.putExtra("user", toUser);
                intent.putExtra("visitorid", sServiceId);
                intent.putExtra("chatGroupId", Long.parseLong(String.valueOf(entty.chatGroupId)));
                intent.putExtra("originType", entty.orginType);
                intent.putExtra("techChannelName", entty.techChannelName);
                startActivity(intent);
                finish();
            }
        });

        mAdapter.addAll(mList);
        mAdapter.sort(new Comparator<HistorySessionEntity>() {
            @Override
            public int compare(HistorySessionEntity lhs, HistorySessionEntity rhs) {
                if (lhs == null || rhs == null) {
                    return 0;
                }
                long ltime = convertStringTimeToLongTime(lhs.createDatetime);
                long rtime = convertStringTimeToLongTime(rhs.createDatetime);
                if (ltime < rtime) {
                    return 1;
                } else if (ltime > rtime) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });

        query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    btnClear.setVisibility(View.VISIBLE);
                } else {
                    btnClear.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mAdapter.clear();
                mAdapter.addAll(filter(mList, editable.toString()));
            }
        });

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                query.getText().clear();
                finish();
            }
        });

        rl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }


    private void getUserInfo(final HistorySessionEntity data) {
//        OkHttpClient okHttpClient = new OkHttpClient();
        String val = data.visitorUser.getUsername();

        if(!TextUtils.isEmpty(val) && val.contains("#")){
            String uid = val.split("#")[0];
            ApiService apiService = HKHttpUtils.getApiService();
            Call<BaseResponse<User>> call = apiService.getUserById(MainActivity.ticket,String.valueOf(uid));
            call.enqueue(new HKResponseResultCallBack<User>() {
                @Override
                public void onSuccess(User user) {
                    if(user != null){
                        if(!TextUtils.isEmpty(user.getName())){
                            data.visitorUser.setNicename(user.getName());
                        }
                    }
                }

                @Override
                public void onGetDataFailed(int cd, String msg) {
                    Toast.makeText(SearchHistorySessionActivity.this, "请求失败:"+msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailed(Call call, Throwable t) {
                    Toast.makeText(SearchHistorySessionActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                }
            });
//            RequestBody body = new FormBody.Builder()
//                    .add("uid", String.valueOf(uid))
//                    .build();
//
//            Request request = new Request.Builder()
//                    .url(BuildConfig.API_URL + "account/findUserById")
//                    .post(body)
//                    .build();
//
//            Call call = okHttpClient.newCall(request);
//
//            call.enqueue(new Callback() {
//                @Override
//                public void onFailure(Call call, IOException e) {
//                    e.printStackTrace();
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(SearchHistorySessionActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                }
//
//                @Override
//                public void onResponse(Call call, Response response) throws IOException {
//
//                    final String res = response.body().string();
//                    final UserInfo result = CommonUtils.parseJsonWithGson(res, UserInfo.class);
//
//                    if(result.getData() != null){
//                        if(!TextUtils.isEmpty(result.getData().getName())){
//                            data.visitorUser.setNicename(result.getData().getName());
//                        }
//                    }
//                }
//            });

        }




    }

    private void initView(){
        recyclerView = (EasyRecyclerView)findViewById(R.id.recyclerView);
        btnClear = (ImageButton)findViewById(R.id.search_clear);
        query = (EditText)findViewById(R.id.query);
        rl_back = (RelativeLayout) findViewById(R.id.rl_back);
        query.setHint("请输入姓名");
    }

    private long convertStringTimeToLongTime(String stringTime) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        try {
            Date parseTime = dateFormat.parse(stringTime);
            return parseTime.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            HDLog.e(TAG, e.getMessage());
        }
        return 0;
    }


    private List<HistorySessionEntity> filter(List<HistorySessionEntity> models, String query){
        query = query.toLowerCase();

        final List<HistorySessionEntity> filteredModelList = new ArrayList<>();
        for(int i=0;i<models.size(); i++) {

            final String text = models.get(i).visitorUser.getNicename().toLowerCase();
            if(text.contains(query)){
                filteredModelList.add(models.get(i));
            }else if(models.get(i).agentUserNiceName.toLowerCase().contains(query)){
                filteredModelList.add(models.get(i));
            }

        }
        return filteredModelList;
    }




}
